#include "networkhelper.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QUrl>
#include <QUrlQuery>
#include <QDebug>

NetworkHelper::NetworkHelper(QObject *parent) : QObject(parent) {
    networkManager = new QNetworkAccessManager(this);
    connect(networkManager, &QNetworkAccessManager::finished,
            this, &NetworkHelper::onNetworkReply);
}

// 搜索音乐
void NetworkHelper::searchMusic(const QString& keyword) {
    QUrl url(kugouSearchApi);
    QUrlQuery query;
    query.addQueryItem("format", "json");
    query.addQueryItem("keyword", keyword);
    query.addQueryItem("page", "1");
    query.addQueryItem("pagesize", "20");
    query.addQueryItem("showtype", "1");
    url.setQuery(query);

    qDebug() << "搜索请求URL:" << url.toString();
    networkManager->get(QNetworkRequest(url));
}

// 获取音乐播放链接 - 添加签名逻辑
void NetworkHelper::getMusicUrl(const QString& album_id, const QString& hash) {
    qDebug() << "请求播放地址的参数：album_id=" << album_id << ", hash=" << hash;

    // 检查参数是否为空
    if (album_id.isEmpty() || hash.isEmpty()) {
        emit errorOccurred("album_id或hash为空，无法获取播放地址");
        return;
    }

    // 生成时间戳
    qint64 timestamp = QDateTime::currentSecsSinceEpoch();

    // 生成签名源字符串
    QString signSource = QString("hash=%1&album_id=%2&appid=%3&version=%4&timestamp=%5&key=%6")
                         .arg(hash)
                         .arg(album_id)
                         .arg(appid)
                         .arg(version)
                         .arg(timestamp)
                         .arg(key);

    // 计算MD5签名
    QString sign = QCryptographicHash::hash(signSource.toUtf8(), QCryptographicHash::Md5).toHex();

    // 确保签名是32位
    if (sign.length() > 32) {
        sign = sign.left(32);
    }
    qDebug() << "签名源字符串:" << signSource;
    qDebug() << "生成的sign:" << sign;

    // 构建URL
    QUrl url(kugouDownloadApi);
    QUrlQuery query;
    query.addQueryItem("r", "play/getdata");
    query.addQueryItem("hash", hash);
    query.addQueryItem("album_id", album_id);
    query.addQueryItem("difid", difid);
    query.addQueryItem("mid", mid);
    query.addQueryItem("platid", platid);
    query.addQueryItem("appid", appid);
    query.addQueryItem("version", version);
    query.addQueryItem("timestamp", QString::number(timestamp));
    query.addQueryItem("sign", sign);
    url.setQuery(query);

    qDebug() << "完整请求URL:" << url.toString();
    networkManager->get(QNetworkRequest(url));
}

void NetworkHelper::onNetworkReply(QNetworkReply* reply) {
    // 获取请求的URL用于区分不同API
    QString url = reply->url().toString();

    // 处理错误
    if (reply->error() != QNetworkReply::NoError) {
        QString errorMsg = QString("网络错误 (%1): %2").arg(reply->error()).arg(reply->errorString());
        emit errorOccurred(errorMsg);
        qDebug() << errorMsg << "URL:" << url;
        reply->deleteLater();
        return;
    }

    // 读取响应数据
    QByteArray data = reply->readAll();

    // 处理搜索结果
    if (url.contains("search/song")) {
        QList<SongInfo> songs = parseSearchJson(data);
        emit searchFinished(songs);
    }
    // 处理播放地址结果
    else if (url.contains("play/getdata")) {
        qDebug() << "===== 播放地址API返回原始数据 =====";
        qDebug() << data;
        qDebug() << "===================================";

        QString lyric;
        QString playUrl = parseMusicJson(data, lyric);
        emit musicUrlReady(playUrl, lyric);
    }else qDebug ()<<"获取失败";

    reply->deleteLater();
}

QList<SongInfo> NetworkHelper::parseSearchJson(const QByteArray& data) {
    QList<SongInfo> songs;
    QJsonParseError jsonError;
    QJsonDocument doc = QJsonDocument::fromJson(data, &jsonError);

    // 检查JSON解析是否成功
    if (jsonError.error != QJsonParseError::NoError) {
        emit errorOccurred("搜索结果解析错误: " + jsonError.errorString());
        qDebug() << "JSON解析错误:" << jsonError.errorString() << "原始数据:" << data;
        return songs;
    }

    if (!doc.isObject()) {
        emit errorOccurred("搜索结果不是有效的JSON对象");
        return songs;
    }

    QJsonObject root = doc.object();
    if (root.contains("data") && root["data"].isObject()) {
        QJsonObject dataObj = root["data"].toObject();
        if (dataObj.contains("info") && dataObj["info"].isArray()) {
            QJsonArray infoArr = dataObj["info"].toArray();
            for (int i = 0; i < infoArr.size(); ++i) {
                QJsonObject songObj = infoArr[i].toObject();
                SongInfo song;
                song.id = i;
                song.songname = songObj["songname"].toString();
                song.singername = songObj["singername"].toString();
                song.album_id = songObj["album_id"].toString();
                song.hash = songObj["hash"].toString();

                // 调试信息
                qDebug() << "解析到歌曲:" << song.songname << "歌手:" << song.singername
                         << "album_id:" << song.album_id << "hash:" << song.hash;

                songs.append(song);
            }
        } else {
            emit errorOccurred("搜索结果中没有找到info数组");
            qDebug() << "搜索结果中没有info数组，原始数据:" << data;
        }
    } else {
        emit errorOccurred("搜索结果中没有找到data对象");
        qDebug() << "搜索结果中没有data对象，原始数据:" << data;
    }

    return songs;
}

QString NetworkHelper::parseMusicJson(const QByteArray& data, QString& lyric) {
    // 初始化返回值
    lyric = "";

    QJsonParseError jsonError;
    QJsonDocument doc = QJsonDocument::fromJson(data, &jsonError);

    // 检查JSON解析是否成功
    if (jsonError.error != QJsonParseError::NoError) {
        emit errorOccurred("播放地址解析错误: " + jsonError.errorString());
        qDebug() << "播放地址JSON解析错误:" << jsonError.errorString();
        return "";
    }

    // 打印解析后的JSON数据
    qDebug() << "解析后的JSON数据：";
    qDebug() << doc.toJson(QJsonDocument::Indented);

    if (!doc.isObject()) {
        emit errorOccurred("播放地址返回不是有效的JSON对象");
        return "";
    }

    QJsonObject root = doc.object();

    // 检查是否有错误码
    if (root.contains("err_code") && root["err_code"].toInt() != 0) {
        int errCode = root["err_code"].toInt();
        QString errMsg = QString("API错误: 错误码 %1").arg(errCode);
        emit errorOccurred(errMsg);
        qDebug() << errMsg;

        // 特定错误码的提示
        if (errCode == 30020) {
            emit errorOccurred("权限不足，请检查签名参数或尝试其他歌曲");
        }
        return "";
    }

    if (root.contains("data") && root["data"].isObject()) {
        QJsonObject dataObj = root["data"].toObject();

        // 提取歌词
        if (dataObj.contains("lyrics")) {
            lyric = dataObj["lyrics"].toString();
        } else {
            lyric = "无歌词";
        }

        // 提取播放地址
        if (dataObj.contains("play_url") && dataObj["play_url"].isString()) {
            QString playUrl = dataObj["play_url"].toString();
            if (playUrl.isEmpty()) {
                emit errorOccurred("未找到有效的播放地址");
                return "";
            }
            return playUrl;
        } else {
            emit errorOccurred("JSON中没有找到play_url字段");
            return "";
        }
    } else {
        emit errorOccurred("播放地址返回中没有找到data对象");
        return "";
    }
}
